package cn.sylinx.horm.core.stat;

import java.util.Iterator;
import java.util.ServiceLoader;

import cn.sylinx.horm.util.GLog;

enum SqlExecutedHandlerManager {

    ;

    private static SqlExecutedHandler sqlExecutedHandler = null;

    static SqlExecutedHandler getSqlExecutedHandler() {

        if (sqlExecutedHandler != null) {
            return sqlExecutedHandler;
        }

        synchronized (SqlExecutedHandlerManager.class) {

            if (sqlExecutedHandler != null) {
                return sqlExecutedHandler;
            }

            ServiceLoader<SqlExecutedHandler> sl = ServiceLoader.load(SqlExecutedHandler.class);
            Iterator<SqlExecutedHandler> it = sl.iterator();
            if (it.hasNext()) {
                sqlExecutedHandler = it.next();
            }

            if (sqlExecutedHandler == null) {

                // 未设置，则打日志
                sqlExecutedHandler = new SqlExecutedHandler() {

                    @Override
                    public void onTimeout(String datasoureName, String nativeSql, long thresholdMillSeconds) {
                        GLog.warn("SQL执行超过[{}]毫秒未返回结果, 数据源：{}， SQL：{}", thresholdMillSeconds, datasoureName, nativeSql);
                    }

                    @Override
                    public void onDone(String datasoureName, String nativeSql, Long usedTime, Throwable error) {
                        if (error != null) {
                            GLog.error("执行SQL --> [{}]异常", nativeSql, error);
                        } else {
                            GLog.debug("执行用时：{}毫秒，数据源：{}，SQL：{}", usedTime, datasoureName, nativeSql);
                        }
                    }
                };
            }
        }

        return sqlExecutedHandler;
    }
}
